package cn.net.dpi.core.validation;

import cn.net.dpi.core.annotation.StartAndStopTime;
import org.springframework.beans.BeanWrapperImpl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author dzcr
 */
public class StartAndStopTimeValidator implements ConstraintValidator<StartAndStopTime, Object> {

    private StartAndStopTime startAndStopTime;

    @Override
    public void initialize(StartAndStopTime constraintAnnotation) {
        this.startAndStopTime = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {

        String startTimeFiled = startAndStopTime.startTimeFiledName();
        String endTimeFiled = startAndStopTime.endTimeFiledName();

        BeanWrapperImpl beanWrapper = new BeanWrapperImpl(value);
        Object startTime = beanWrapper.getPropertyValue(startTimeFiled);
        Object endTime = beanWrapper.getPropertyValue(endTimeFiled);

        if (startTime == null || endTime == null) {
            return false;
        }

        if (Date.class.isAssignableFrom(startTime.getClass())
                && Date.class.isAssignableFrom(endTime.getClass())) {
            return ((Date) startTime).before((Date) endTime);
        }

        if (LocalDateTime.class.isAssignableFrom(startTime.getClass())
                && LocalDateTime.class.isAssignableFrom(endTime.getClass())) {
            return ((LocalDateTime) startTime).isBefore((LocalDateTime) endTime);
        }

        return false;
    }
}
